﻿#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;

#endregion

namespace FastTrackCabService.AdminPanel
{
    public partial class VehicleRegistrationForm : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                foreach (var subsidiary in SubsidiaryBLL.GetAllSubsidiaries().OrderBy(sub => sub.CityId))
                {
                    var city = CityBLL.GetCityById(subsidiary.CityId);
                    var item = new ListItem(city.Name, subsidiary.SubsidiaryId.ToString());
                    ddlSubsidiary.Items.Add(item);
                }

                LoadSupervisors();
            }
        }

        private void LoadSupervisors()
        {
            var listOfSupervisors = new List<ListItem>();

            foreach (
                var supervisor in
                    SupervisorBLL.GetAllSupervisors()
                        .Where(
                            sup =>
                                sup.SupervisorType == "Vehicles supervisor" &&
                                StaffBLL.GetStaffById(sup.StaffId).SubsidiaryId ==
                                Convert.ToByte(ddlSubsidiary.SelectedValue)))
            {
                var staff = StaffBLL.GetStaffById(supervisor.StaffId);
                var item = new ListItem(staff.FirstName, supervisor.StaffId.ToString());
                listOfSupervisors.Add(item);
            }

            var sortedListOfSupervisors = listOfSupervisors.OrderBy(item => item.Text);
            ddlSupervisor.DataSource = sortedListOfSupervisors;
            ddlSupervisor.DataTextField = "Text";
            ddlSupervisor.DataValueField = "Value";
            ddlSupervisor.DataBind();
        }

        protected void btnRegister_OnClick(object sender, EventArgs e)
        {
            if (IsValid)
            {
                VehicleBLL.RegisterVehicle(tbRegNo.Text, Convert.ToByte(ddlSubsidiary.SelectedValue),
                    Convert.ToInt32(ddlSupervisor.SelectedValue), ddlType.SelectedValue);
                Response.Redirect("Vehicles.aspx");
            }
        }

        protected void tbRegNo_OnTextChanged(object sender, EventArgs e)
        {
            cvRegNo.Validate();
        }

        protected void cvRegNo_OnServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = !VehicleBLL.IsAlreadyRegistered(tbRegNo.Text);
        }

        protected void ddlSubsidiary_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            LoadSupervisors();
        }
    }
}